package cn.lzj.basic.controller;

import cn.lzj.basic.util.AjaxResult;
import cn.lzj.basic.util.FastDfsUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 上传: 需要
 * 下载:不需要
 * 删除:需要
 * 修改:不需要=删除+上传
 */
@RestController
@RequestMapping("/fastdfs")
//el-uoload提供的文件上传默认name=false
public class FastDfsController {
    /**
     * 上传接口
     * @param file
     * @return
     */
    @PostMapping
    public AjaxResult upload(@RequestPart MultipartFile file) {
        try {
            String originalFilename = file.getOriginalFilename();
            String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            String filename = FastDfsUtil.upload(file.getBytes(), extName);
           //将上传之后的名字响应给前端
            return AjaxResult.util().setResultObj(filename);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.util()
                    .setsuccess(false)
                    .setmessage("上传失败！！!");
        }
    }
    @DeleteMapping
    //前端传回字符串,调接口删掉
    public AjaxResult del(@RequestParam String path){
        try {
            String pathTmp = path.substring(1);
            String group = pathTmp.substring(0, pathTmp.indexOf("/"));
            String filePath = pathTmp.substring(pathTmp.indexOf("/") + 1);
            //调用删除接口
            FastDfsUtil.delete(group,filePath);
            return new AjaxResult();
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.util()
                    .setsuccess(false)
                    .setmessage("上传失败！！!");
        }
    }
}